package gitobject;

import JitUtils.FileHash;

import java.io.*;

public class Blob extends GitObject{
    
	public String getFmt(){
        return fmt;
    }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }
    public String getKey() { return key; }
    public Blob(){};
    /**
     * Constructing blob object from a file
     * @param file
     * @throws Exception
     */
    public Blob(File file, String s) throws Exception {
        fmt = "blob";
        mode = "100644";
        value = getValue(file);
        genKey(file,s);
    }

    /**
     * Deserialize a blob object from an existed hash file in .jit/objects.
     * @param path
     * @throws IOException
     */
    public static Blob deserialize(String path) throws IOException {
        ObjectInputStream ois = null;
        Blob blob = null;
        try{
            ois = new ObjectInputStream(new FileInputStream(path));
            blob = (Blob) ois.readObject();
            return blob;
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if(ois != null){
                try {
                    ois.close();;
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return blob;
    }

    /**
     * Generate key from file.
     * @param file
     * @return String
     * @throws Exception
     */
    public String genKey(File file,String s) throws Exception {
        key = FileHash.fileHash(file,s).getId();
        return key;
    }

    @Override
    public String toString(){
        return "100644 blob " + key;
    }
}
